package com.fierce.cloud.ota.controller;

import com.fierce.cloud.ota.dao.VersionInfoMapper;
import com.fierce.cloud.ota.model.OtaResponse;
import com.fierce.cloud.ota.model.VersionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: Fierce
 * @Date: 2021/2/21 14:26
 */
@RestController
@RequestMapping("/client")
public class OtaController {

    @Autowired
    VersionInfoMapper versionInfoMapper;

    @Value("${spring.redis.host}")
    private String host;

    @Value("${server.port}")
    private String port;

    /**
     * @return {
     * "Code": 0, //0代表请求成功，非0代表失败
     * "Msg": "", //请求出错的信息
     * "UpdateStatus": 1, //0代表不更新，1代表有版本更新，不需要强制升级，2代表有版本更新，需要强制升级
     * "VersionCode": 3,
     * "VersionName": "1.0.2",
     * "ModifyContent": "1、优化api接口。\r\n2、添加使用demo演示。\r\n3、新增自定义更新服务API接口。\r\n4、优化更新提示界面。",
     * "DownloadUrl": "https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk",
     * "ApkSize": 2048
     * "ApkMd5": "..."  //md5值没有的话，就无法保证apk是否完整，每次都会重新下载。框架默认使用的是md5加密。
     * }
     */
    @GetMapping("/update/{appId}")
    public OtaResponse getOtaResponse(@PathVariable Long appId, Long currentVersionCode) {

        OtaResponse otaResponse = new OtaResponse();
        VersionInfo versionInfo = versionInfoMapper.selectNewestVersionByAppId(appId);
        otaResponse.setCode(0);
        otaResponse.setMsg("请求成功");
        if (versionInfo == null) {
            otaResponse.setUpdateStatus(0);
            otaResponse.setVersionCode(0);
            otaResponse.setVersionName("No Version");
            otaResponse.setModifyContent("No Version");
            otaResponse.setDownloadUrl("No Version");
            otaResponse.setApkSize(0);
        } else {
            if (versionInfo.getVersionCode() > currentVersionCode) {
                otaResponse.setUpdateStatus(1);
            } else {
                otaResponse.setUpdateStatus(0);
            }
            otaResponse.setVersionCode(versionInfo.getVersionCode());
            otaResponse.setVersionName(versionInfo.getVersionName());
            otaResponse.setModifyContent(versionInfo.getModifyContent());
            otaResponse.setDownloadUrl("http://" + host + ":" + port + versionInfo.getDownloadUrl());
            otaResponse.setApkSize(versionInfo.getSize().intValue() / 1024);
        }
        otaResponse.setApkMd5("");
        return otaResponse;
    }
}
